package com.opgea.crm.repository;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.domain.entities.Activity;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.Issue;
import com.opgea.crm.domain.entities.Task;

@Repository
public class CalenderRepoImpl implements CalenderRepo {

	
	@PersistenceContext
	private EntityManager em;
	@Override
	public List<Activity> showCalenderGrid(Long assignToId, Date pfrom,Date pto) {
		 StringBuffer buffer=new StringBuffer("SELECT a FROM Activity a ");
		 String cond=" WHERE ";
			if(assignToId!=null){
			  buffer.append(cond);
			  buffer.append(" a.assignTo.id="+assignToId);
			  cond=" AND ";
			}
			if(pfrom!=null && pto!=null)
			{
				buffer.append(cond);
				buffer.append(" a.startTime:st BETWEEN a.startTime: ed");
				
			}
			
			Query query=em.createQuery(buffer.toString());
			return query.getResultList();
	}

	
	
	@Override
	public List<Task> showCalenderTaskGrid(Long assignToId, Date pfrom, Date pto) {
		StringBuffer buffer=new StringBuffer("SELECT t FROM Task t ");
		 String cond=" WHERE ";
			if(assignToId!=null){
			  buffer.append(cond);
			  buffer.append(" t.assignTo.id="+assignToId);
			  cond=" AND ";
			}
			if(pfrom!=null && pto!=null)
			{
				buffer.append(cond);
				buffer.append(" t.createdAt:st BETWEEN t.createdAt: ed");
				
			}
			
			Query query=em.createQuery(buffer.toString());
			return query.getResultList();
		
	}


	
	

	@Override
	public List<Issue> showCalenderIssueGrid(Long assignToId, Date pfrom,Date pto) {
		StringBuffer buffer=new StringBuffer("SELECT i FROM Issue i ");
		 String cond=" WHERE ";
			if(assignToId!=null){
			  buffer.append(cond);
			  buffer.append(" i.assignedTo.id="+assignToId);
			  cond=" AND ";
			}
			if(pfrom!=null && pto!=null)
			{
				buffer.append(cond);
				buffer.append(" i.createdAt:st BETWEEN i.createdAt: ed");
				
			}
			
			Query query=em.createQuery(buffer.toString());
			return query.getResultList();
	}



	public List<Employee> getAssignTo(ApplicationConstant.SalesCalenderType type)
	{
		StringBuffer buffer=new StringBuffer("SELECT a.assignTo FROM ");
		if(type.equals(ApplicationConstant.SalesCalenderType.Activity))
		{
			buffer.append("Activity a GROUP BY(a.assignTo.id)");
		}
		if(type.equals(ApplicationConstant.SalesCalenderType.Task))
		{
			buffer.append("Task a GROUP BY(a.assignTo.id)");
		}
		if(type.equals(ApplicationConstant.SalesCalenderType.Issue))
		{
			buffer.append("Issue a GROUP BY(a.assignedTo.id)");
		}
		Query query=em.createQuery(buffer.toString());
		return query.getResultList();
	}
}
